package com.punai.config.sqlitedao;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.punai.common.core.page.TableDataInfo;
import com.punai.common.exception.base.BaseException;
import com.punai.common.utils.StringUtils;
import com.punai.common.utils.sqlite.SqliteUtils;
import com.punai.config.sqlitedomain.ConfigIndicatorItem;
import com.punai.config.sqlitedomain.vo.ConfigIndicatorItemVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class IndicatorItemRepository {
    @Autowired
    private SqliteUtils sqliteUtils;
    public List<ConfigIndicatorItem> findAllByModel(ConfigIndicatorItemVo vo) {
        String selSql="select * from tab_config_indicator_item";
        String whereSql="where 1=1";
        if(StringUtils.isNotEmpty(vo.getClassification()))  whereSql+=" and classification='"+vo.getClassification()+"'";
        if(StringUtils.isNotEmpty(vo.getType()))            whereSql+=" and type='"+vo.getType()+"'";
        String sql=selSql+" "+whereSql;
        if(vo.getPageNum()!=null&&vo.getPageSize()!=null){
            int pageNumber = vo.getPageNum();
            int pageSize = vo.getPageSize();
            int start = pageSize * (pageNumber-1);
            sql += " limit " + start + "," + pageSize;
        }
        return sqliteUtils.selectListRecord(ConfigIndicatorItem.class, sql);
    }

    public ConfigIndicatorItem findOneById(String id) {
        String selSql = "select * from tab_config_indicator_item";
        String whereSql = "where id='"+id+"'";
        String sql = selSql + " " + whereSql;
        return sqliteUtils.selectOneRecord(ConfigIndicatorItem.class, sql);
    }

    public ConfigIndicatorItem findOneByCode(String code) {
        String selSql = "select * from tab_config_indicator_item";
        String whereSql = "where code='" + code + "'";
        String sql = selSql + " " + whereSql;
        return sqliteUtils.selectOneRecord(ConfigIndicatorItem.class, sql);
    }

    public int countByModel(ConfigIndicatorItemVo vo) {
        String selSql = "select count(*) as total from tab_config_indicator_item";
        String whereSql = "where 1=1";
        if (StringUtils.isNotEmpty(vo.getClassification()))
            whereSql += " and classification='" + vo.getClassification() + "'";
        if (StringUtils.isNotEmpty(vo.getType())) whereSql += " and type='" + vo.getType() + "'";
        String sql = selSql + " " + whereSql;
        Map unique = sqliteUtils.unique(sql);
        return Integer.parseInt(unique.get("total").toString());
    }

    public ConfigIndicatorItemVo save(ConfigIndicatorItemVo vo) {
        if(StringUtils.isNotEmpty(vo.getId())) return this.update(vo);
        ConfigIndicatorItem oneByCode = this.findOneByCode(vo.getCode());
        if(oneByCode!=null) throw new BaseException("编码重复");
        String sql="insert into tab_config_indicator_item(" +
                "ID,CODE,NAME," +
                "UNIT,IS_GROUP_DATA,CLASSIFICATION," +
                "TYPE,CREATE_DATE,EDIT_STATE,LAST_MODIFY," +
                "SREACH_KEY,VERSION,SCRIPT,CONSUMPTION_SCRIPT," +
                "DEPART_CODE,PROJECT_TYPE,COSTS_TYPE,ATTR," +
                "CALCULATE_CALIBER_TYPE,CONDITIONS,CONVER_COEFFICIENT," +
                "REMARK,QD_CODES,QD_ID_STR,FORMULA," +
                "EXCLUDE_QD_CODES,EXCLUDE_QD_ID_STR," +
                "IMPORTANT) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ";
        vo.setId(UUID.randomUUID().toString());
        vo.setCreateDate(new Date());
        vo.setLastModify(new Date());
        vo.setSreachKey(vo.toString());
        vo.setEditState(0L);
        Object [] args={
                vo.getId(),
                vo.getCode(),
                vo.getName(),
                vo.getUnit(),
                vo.getIsGroupData(),
                vo.getClassification(),
                vo.getType(),
                vo.getCreateDate(),
                vo.getEditState(),
                vo.getLastModify(),
                vo.getSreachKey(),
                vo.getVersion(),
                vo.getScript(),
                vo.getConsumptionScript(),
                vo.getDepartCode(),
                vo.getProjectType(),
                vo.getCostsType(),
                vo.getAttr(),
                vo.getCalculateCaliberType(),
                vo.getConditions(),
                vo.getConverCoefficient(),
                vo.getRemark(),
                vo.getQdCodes(),
                vo.getQdIdStr(),
                vo.getFormula(),
                vo.getExcludeQdCodes(),
                vo.getExcludeQdIdStr(),
                vo.getImportant()
        };
        int execute = sqliteUtils.execute(sql, args);
        if(execute==0){
            throw new BaseException("IndicatorItemRepository.sava失败");
        }
        return vo;
    }

    public ConfigIndicatorItemVo update(ConfigIndicatorItemVo vo) {
        ConfigIndicatorItem oneByCode = this.findOneByCode(vo.getCode());
        if (oneByCode != null && !StrUtil.equals(oneByCode.getId(),vo.getId())) throw new BaseException("编码重复");
        String sql="update tab_config_indicator_item set " +
                "code = ?," +
                "name = ?," +
                "unit = ?," +
                "remark = ?," +
                "formula = ?," +
                "calculate_caliber_type = ?," +
                "important = ?," +
                "LAST_MODIFY = ?," +
                "SREACH_KEY = ? " +
                "where id = ?";
        vo.setLastModify(new Date());
        vo.setSreachKey(vo.toString());
        Object[] args = {
                vo.getCode(),
                vo.getName(),
                vo.getUnit(),
                vo.getRemark(),
                vo.getFormula(),
                vo.getCalculateCaliberType(),
                vo.getImportant(),
                vo.getLastModify(),
                vo.getSreachKey(),
                vo.getId()
        };
        int execute = sqliteUtils.execute(sql, args);
        if (execute == 0) {
            throw new BaseException("IndicatorItemRepository.update失败");
        }
        return vo;
    }

    public ConfigIndicatorItem delete(String id) {
        ConfigIndicatorItem one = this.findOneById(id);
        if(one==null) throw new BaseException("IndicatorItemRepository.delete失败");
        String sql="delete from tab_config_indicator_item where id = ?";
        Object[] args = {
                id
        };
        int execute = sqliteUtils.execute(sql, args );
        if (execute == 0) {
            throw new BaseException("IndicatorItemRepository.delete失败");
        }
        return one;
    }

    public ConfigIndicatorItem settingUnitConver(ConfigIndicatorItemVo vo) {
        ConfigIndicatorItem one = this.findOneById(vo.getId());
        String sql = "update tab_config_indicator_item set " +
                "CONVER_COEFFICIENT = ?," +
                "LAST_MODIFY = ?," +
                "SREACH_KEY = ? " +
                "where id = ?";
        one.setConverCoefficient(vo.getConverCoefficient());
        one.setLastModify(new Date());
        one.setSreachKey(vo.toString());
        Object[] args = {
                one.getConverCoefficient(),
                one.getLastModify(),
                one.getSreachKey(),
                one.getId()
        };
        int execute = sqliteUtils.execute(sql, args);
        if (execute == 0) {
            throw new BaseException("IndicatorItemRepository.settingUnitConver失败");
        }
        return one;
    }

    public ConfigIndicatorItem settingMatchingRules(ConfigIndicatorItem vo) {
        ConfigIndicatorItem one = this.findOneById(vo.getId());
        String sql = "update tab_config_indicator_item set " +
                "QD_ID_STR = ?," +
                "EXCLUDE_QD_ID_STR=?,"+
                "CONDITIONS = ?," +
                "LAST_MODIFY = ?," +
                "SREACH_KEY = ? " +
                "where ID = ?";
        one.setConditions(vo.getConditions());
        one.setLastModify(new Date());
        one.setSreachKey(one.toString());
        one.setQdIdStr(vo.getQdIdStr());
        one.setExcludeQdIdStr(vo.getExcludeQdIdStr());
        Object[] args = {
                one.getQdIdStr(),
                one.getExcludeQdIdStr(),
                one.getConditions(),
                one.getLastModify(),
                one.getSreachKey(),
                one.getId()
        };
        int execute = sqliteUtils.execute(sql, args);
        if (execute == 0) {
            throw new BaseException("IndicatorItemRepository.settingMatchingRules失败");
        }
        return one;
    }

    public TableDataInfo selectNoUsedItem(String structId, String indicatorType, Integer pageNumber, Integer pageSize) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        int pNum= pageNumber - 1;
        /*
         * CLASSIFICATION:0是清单，1是人材机
         * type：1是比值，2是费用项，3是成本费用项
         */
        /* 指标表结构  -   指标项要求
        * 0:分部分项清单 : 清单 + 比值
          1:人材机 : 人材机 + 比值
          2:费用项 :  费用项
          3:措施项目清单 : 清单 + 比值
          4:成本费用 : 成本费用项
          * */

        String wheresql = " where tclsi.id is null ";

        if (StrUtil.startWith(indicatorType,"t")) {
            String type = indicatorType.replace("t_","");
            wheresql += " and tcii.type = '" + type + "' ";
        } else {
            String classification = indicatorType.replace("c_","");
            wheresql += " and tcii.CLASSIFICATION = '" + classification + "' ";
        }

        // 使用过不展示
        String orderBySql = " order by tcii.CREATE_DATE ";
        String pageSql = "  limit " + pNum * pageSize + "," + pageSize;
        String selectSql = "select tcii.* from tab_config_indicator_item tcii left join tab_config_link_struts_item tclsi on tcii.id = tclsi.ELEMENT_ID and tclsi.STRUTS_ID = '" + structId + "' " + wheresql + orderBySql + pageSql;
        String selectCountSql = "select count(tcii.id) as ICOUNT  from tab_config_indicator_item tcii left join tab_config_link_struts_item tclsi on tcii.id = tclsi.ELEMENT_ID and tclsi.STRUTS_ID = '" + structId + "' " + wheresql  + orderBySql;

        Map unique = sqliteUtils.unique(selectCountSql);
        Long icount = Convert.toLong(unique.get("ICOUNT"));
        tableDataInfo.setTotal(icount);

        List<ConfigIndicatorItem> configIndicatorItems = sqliteUtils.selectListRecord(ConfigIndicatorItem.class, selectSql);
        tableDataInfo.setRows(configIndicatorItems);
        return tableDataInfo;
    }

    public List<ConfigIndicatorItem> findByIdIn(List<String> ids) {
        String sql = "SELECT * FROM tab_config_indicator_item WHERE ID IN('"+ StrUtil.join("','",ids) + "')";
        return sqliteUtils.selectListRecord(ConfigIndicatorItem.class, sql);
    }
}
